import React, { memo, useEffect, useState } from "react";
import { Commentwrap } from "./style";
import { DownOutlined } from "@ant-design/icons";
import { Input, Dropdown, Menu, Space, message } from "antd";
import {
  byessay,
  deletecommentapi,
  replyapi,
  thumbcommentapi,
} from "@/apis/comment";
import { useNavigate, useParams } from "react-router-dom";
import classnames from "classnames";
import { formattime } from "@/utils";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { rootState } from "@/store";
import { usertype } from "@/store/reducers/home";
import { getcollectidarraction, loginpatch } from "@/store/action/home";
export interface commentstate {
  id: number;
  author: {
    id: number;
    avatar: string;
    username: string;
  };
  childcomment: commentstate[];
  comment_id: null | number;
  createAt: string;
  essay_id: number;
  user_id: number;
  content: string;
  thumbcount: number;
  replyname?: string;
}
const { TextArea } = Input;

function Comment() {
  const { id } = useParams();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  //评论内容
  const [comment, setComment] = useState<commentstate[]>([]);
  //回复的对象
  const [replyobj, setRlyobj] = useState<{
    commentid: number;
    content: string;
  }>({ commentid: -1, content: "" });
  // 评论框的placehoder
  const [placeholder, setPlaceHolder] = useState<string>("请发表和善的评论");
  //保存回复的评论是否展开
  const [expand, setExpand] = useState<boolean[]>();
  //当前用户点赞评论的数组和当前用户id
  const { commentarr, user } = useSelector((store: rootState) => {
    return {
      commentarr: store.home.thumbdobj.commentarr,
      user: store.home.user as usertype,
    };
  }, shallowEqual);
  useEffect(() => {
    getallfn();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);
  //当评论数据改变时，重新计算是否展开（避免没有回复评论的评论了）
  useEffect(() => {
    //说明是初始化
    if (!expand) {
      setExpand(Array(comment.length).fill(false));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [comment]);
  //评论框内容改变
  const onChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setRlyobj((c) => ({ ...c, content: e.target.value }));
  };
  //改变回复评论对象
  const changereply = (id: number, person: string) => {
    if (!user.id) return message.warning("请登录");
    setRlyobj((c) => ({ ...c, commentid: id }));
    setPlaceHolder("回复 @" + person);
  };
  //取消回复
  const canclereply = () => {
    setRlyobj((c) => ({ ...c, commentid: -1 }));
    setPlaceHolder("请发表和善的评论");
  };
  //回复评论
  const reply = async () => {
    if (!user.id) return message.warning("请登录");
    if (replyobj.content === "") return;
    try {
      await replyapi(
        replyobj.content,
        user.id,
        replyobj.commentid,
        parseInt(id as string)
      );
      //说明在最上面添加了一条评论，要保持展开的状态
      if (replyobj.commentid === -1 && expand) {
        setExpand([false, ...expand?.slice()]);
      }
      setRlyobj({ commentid: -1, content: "" });
      setPlaceHolder("请发表和善的言论");
      getallfn();
    } catch (e) {
      dispatch(loginpatch({}));
      message.error("身份失效");
    }
  };
  //删除评论
  const deletecomment = async (comid: number) => {
    if (!user.id) return message.warning("请登录");
    try {
      await deletecommentapi(comid);
      // 保证展开状态
      const index = comment.map((item) => item.id).indexOf(comid);
      if (index > -1 && expand) {
        setExpand([...expand?.slice(0, index), ...expand.slice(index + 1)]);
      }
      getallfn();
    } catch (e) {
      dispatch(loginpatch({}));
      message.error("身份失效");
    }
  };

  //点赞或取消点赞
  const cancelthumb = async (type: number, commentid: number) => {
    if (!user.id) return message.warning("请登录");
    try {
      await thumbcommentapi(type, user.id, commentid);
      getallfn();
      dispatch<any>(getcollectidarraction(user.id));
    } catch (e) {
      dispatch(loginpatch({}));
      message.error("身份失效");
    }
  };
  //获取所有评论
  const getallfn = () => {
    byessay(id as string).then((res: any) => {
      setComment(res.result);
    });
  };
  return (
    <Commentwrap>
      <TextArea
        showCount
        maxLength={100}
        style={{ height: 120 }}
        onChange={onChange}
        value={replyobj.content}
        placeholder={placeholder}
      />
      <div className="bottom">
        {replyobj.commentid !== -1 && (
          <span className="cancelreply" onClick={canclereply}>
            取消回复
          </span>
        )}
        <span
          onClick={reply}
          className={classnames({
            reply: true,
            replyactive: replyobj.content === "",
          })}
        >
          评论
        </span>
      </div>
      <div className="content">
        {comment.length > 0 &&
          comment.map((item, i) => (
            <div className="onecomment" key={item.id}>
              <div className="line">
                <img
                  src={item.author.avatar}
                  onClick={(e) => navigate(`/userpage/${item.author.id}`)}
                  alt=""
                />
                <div className="main">
                  <div className="username">{item.author.username}</div>
                  <div className="comment">{item.content}</div>
                  <div className="time">
                    {formattime(item.createAt)}
                    <span
                      className={
                        commentarr.includes(item.id)
                          ? "iconfont icon-jushoucanggift active"
                          : "iconfont icon-jushoucanggift"
                      }
                      onClick={(e) => {
                        cancelthumb(
                          commentarr.includes(item.id) ? 0 : 1,
                          item.id
                        );
                      }}
                    ></span>
                    <span>{item.thumbcount}</span>
                  </div>
                </div>
                <Dropdown
                  className="dropdown"
                  overlay={
                    <Menu
                      items={[
                        {
                          label: (
                            <div
                              className="reply"
                              style={{ color: "blue" }}
                              onClick={(e) => {
                                changereply(item.id, item.author.username);
                              }}
                            >
                              回复
                            </div>
                          ),
                          key: "0",
                        },
                        {
                          label: user.id === item.user_id && (
                            <div
                              className="delete"
                              style={{ color: "red" }}
                              onClick={(e) => {
                                deletecomment(item.id);
                              }}
                            >
                              删除
                            </div>
                          ),
                          key: "1",
                        },
                      ]}
                    />
                  }
                  trigger={["click"]}
                >
                  <Space>
                    <DownOutlined style={{ cursor: "pointer" }} />
                  </Space>
                </Dropdown>
              </div>
              {expand && item.childcomment && item.childcomment.length > 0 && (
                <span
                  className="expand"
                  onClick={(e) => {
                    const cur = expand.slice();
                    cur[i] = !cur[i];
                    setExpand(cur);
                  }}
                >
                  {expand[i]
                    ? "收起" + item.childcomment?.length + "条回复"
                    : "展开" + item.childcomment?.length + "条回复"}
                </span>
              )}
              {expand &&
                expand[i] &&
                item.childcomment?.map((childitem) => (
                  <div className="line" key={childitem.id}>
                    <img src={childitem.author.avatar} alt="" />
                    <div className="main">
                      <div className="username">
                        {childitem.author.username}
                        <span className="replyname">
                          {childitem.replyname &&
                            "回复 @" + childitem.replyname}
                        </span>
                      </div>
                      <div className="comment">{childitem.content}</div>
                      <div className="time">
                        {formattime(childitem.createAt)}
                        <span
                          className={
                            commentarr.includes(childitem.id)
                              ? "iconfont icon-jushoucanggift active"
                              : "iconfont icon-jushoucanggift"
                          }
                          onClick={(e) => {
                            cancelthumb(
                              commentarr.includes(childitem.id) ? 0 : 1,
                              childitem.id
                            );
                          }}
                        ></span>
                        <span>{childitem.thumbcount}</span>
                      </div>
                    </div>
                    <Dropdown
                      className="dropdown"
                      overlay={
                        <Menu
                          items={[
                            {
                              label: (
                                <div
                                  className="reply"
                                  style={{ color: "blue" }}
                                  onClick={(e) => {
                                    changereply(
                                      childitem.id,
                                      childitem.author.username
                                    );
                                  }}
                                >
                                  回复
                                </div>
                              ),
                              key: "0",
                            },
                            {
                              label: user.id === childitem.user_id && (
                                <div
                                  className="delete"
                                  style={{ color: "red" }}
                                  onClick={(e) => {
                                    deletecomment(childitem.id);
                                  }}
                                >
                                  删除
                                </div>
                              ),
                              key: "1",
                            },
                          ]}
                        />
                      }
                      trigger={["click"]}
                    >
                      <Space>
                        <DownOutlined style={{ cursor: "pointer" }} />
                      </Space>
                    </Dropdown>
                  </div>
                ))}
            </div>
          ))}
      </div>
    </Commentwrap>
  );
}
export default memo(Comment);
